import React, { useState, useEffect } from 'react';
import {
    Button,
    Drawer,
    Form,
    Input,
    Select,
    InputNumber,
    Image,
    message,
    Space,
    Progress,
} from 'antd';
import request from '../request';
import { KodoRootDir, KodoServerDomain, options } from '../config';
import { uploadFile } from '../utils/qiniu';

const formLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
};

function AddBook(props) {

    const [form] = Form.useForm();
    const [fileUrl, setFileUrl] = useState();
    const [file, setFile] = useState(null);
    const [progress, setProgress] = useState(0);

    const { isShow, setIsShow, curBook, getBookList, setCurBook } = props;

    const handleClose = () => {
        setIsShow(false);
        form.resetFields();
        setFileUrl(null);
    };

    useEffect(() => {
        if (curBook && isShow) {
            // 设置表单字段
            form.setFieldsValue({
                desc: curBook.desc,
                price: curBook.price,
                stock: curBook.stock,
                bookName: curBook.bookName,
                category: curBook.category,
            });
            setFileUrl(curBook.url);
        }
    }, [curBook, isShow, form]);

    const handleFileChange = (e) => {
        const { files } = e.target;
        if (files && files.length) {
            setFile(files[0]);
            const fileURL = URL.createObjectURL(files[0]);
            setFileUrl(fileURL);
        } else {
            setFileUrl(null);
            setFile(null);
        }
    };

    const closeModal = (msg) => {
        // 清除表单，管理抽屉，刷新列表
        setIsShow(false);
        setFile(null);
        form.resetFields();
        setFileUrl(null);
        setCurBook(null);
        getBookList();
        message.success(msg);
    };

    const updateFields = (fields) => {
        request.post('/api/update', fields).then(() => {
            // 清除表单，管理抽屉，刷新列表
            closeModal('更新成功');
        });
    };

    // 更新
    const updateFileInfo = (id, values) => {
        const { pic, ...rest } = values;
        if(file) {
            const FilePath = `${KodoRootDir}/${file.name}`;
            request.get('/api/delFile', {
                params: { key: curBook.key },
            }).then(() => {
                uploadFile(file, FilePath, {
                    onProgress(pInfo) {
                        setProgress(Math.round(pInfo.total.percent));
                    },
                    onSuccess(result, { width, height }) {
                        // 把数据存入数据库中
                        const { key, hash } = result;
                        updateFields({
                            ...rest,
                            id,
                            filename: file.name,
                            url: `${KodoServerDomain}/${FilePath}`,
                            key,
                            hash,
                            width,
                            height,
                        });
                    }
                });
            });
        } else {
            updateFields({ ...rest, id });
        }
    };

    const handleSubmit = () => {
        if (!file && !curBook) {
            return message.error('请选择文件');
        }
        // 这里需要判断是更新还是新增
        // 如果是更新，需要先删除之前的文件，然后上传新的文件再更新，，
        form.validateFields().then(values => {
            if (curBook) {
                updateFileInfo(curBook._id, values);
            } else {
                const FilePath = `${KodoRootDir}/${file.name}`;
                const { pic, ...rest } = values;
                // 先上传文件，再把数据存入数据库中
                uploadFile(file, FilePath, {
                    onProgress(pInfo) {
                        setProgress(Math.round(pInfo.total.percent));
                    },
                    onSuccess(result, { width, height }) {
                        // 把数据存入数据库中
                        const { key, hash } = result;
                        request.post('/api/newBook', {
                            ...rest,
                            filename: file.name,
                            url: `${KodoServerDomain}/${FilePath}`,
                            key,
                            hash,
                            width,
                            height,
                        }).then(() => {
                            // 清除表单，管理抽屉，刷新列表
                            closeModal('添加成功');
                        });
                    }
                });
            }
        });
    };

    return (
        <Drawer
            width={600}
            visible={isShow}
            title={curBook ? '更新图书信息' : '添加图书信息'}
            onClose={handleClose}
        >
            <Form form={form} {...formLayout} initialValues={{ stock: 1 }}>

                <Form.Item label="价格" name="price" rules={[{ required: true, message: '价格不能为空' }]}>
                    <InputNumber max={100} min={0} type="number" placeholder="价格" />
                </Form.Item>

                <Form.Item label="库存" name="stock">
                    <InputNumber max={10} min={0} type="number" placeholder="库存" />
                </Form.Item>

                <Form.Item label="书名" name="bookName" rules={[{ required: true, message: "书名不能为空" }]}>
                    <Input placeholder="请输入书名" />
                </Form.Item>

                <Form.Item label="类别" name="category">
                    <Select mode="tags" options={options} placeholder="请选择类别" />
                </Form.Item>

                <Form.Item label="描述" name="desc">
                    <Input.TextArea placeholder="请输入描述信息" />
                </Form.Item>

                <Form.Item label="图片" name="pic">
                    <Input type="file" accept="image/*" onChange={handleFileChange} />
                </Form.Item>

                <Form.Item label="&nbsp;" colon={false}>
                    <Space size="middle">
                        <Button type="primary" onClick={handleSubmit}>提交</Button>
                        <Progress
                            style={{
                                width: 200,
                                display: progress > 0 && progress < 100 ? 'block' : 'none'
                            }}
                            percent={progress}
                        />
                    </Space>
                </Form.Item>

                <Form.Item label="&nbsp;" colon={false}>
                    <Image width={360} src={fileUrl} />
                </Form.Item>
            </Form>
        </Drawer>
    );
}

export default AddBook;
